const { SimpleData, SuccessData } = require('../common/returnDataFormat');
const Topic = require('../model/topic');
const User = require('../model/user');
const sequelize = require('sequelize');
const seq = require('../config/sequelize');
const Types = require('../model/type');
const Comment = require('../model/comment');
const { findOneUser } = require('./userController');
const res = require('express/lib/response');
//发表文章
module.exports.postTopic = async (params) => {
  const result = (
    await Topic.create({
      ...params,
    })
  ).get({
    plain: true,
  });
  return SuccessData(result);
};
//查看指定文章
module.exports.findOneTopic = async (topic_id) => {
  const result = (
    await Topic.findOne({
      include: [
        {
          model: User,
          attributes: ['username', 'user_level'],
        },
        {
          model: Comment,
          include: [
            {
              model: User,
            },
            {
              model: Comment,
              as: 'Comments',
              include: [
                {
                  model: User,
                },
              ],
            },
          ],
          attributes: {
            exclude: ['updated_time'],
          },
        },
      ],
      where: {
        topic_id,
      },
    })
  ).get({ plain: true });
  result.comments = result.comments.filter((item) => {
    return item.replayId == null;
  });
  return result;
};

// 分页查询文章列表
module.exports.getPagingTopic = async ({ offset, limit, type }) => {
  offset = (offset - 1) * limit;
  let where = {};
  if (type) {
    where['type'] = type;
  }
  try {
    const result = await Topic.findAndCountAll({
      where,
      include: [
        {
          model: User,
          attributes: ['username', 'user_id', 'avatar_url'],
        },
        {
          model: Comment,
        },
      ],
      order: [['created_time', 'DESC']],
      limit,
      offset,
    });
    const count = (
      await Topic.findAndCountAll({
        where,
      })
    ).count;
    result.count = count;
    return result;
  } catch (error) {
    console.log(error);
  }
};

//修改文章
module.exports.modifyTopic = async (params, topicId) => {
  const result = await Topic.update(
    {
      ...params,
    },
    {
      where: {
        topic_id: topicId,
      },
    }
  );
  if (result[0]) {
    return SimpleData(200, '修改文章成功');
  }
};
//删除文章
module.exports.deleteTopic = async (topic_id) => {
  const t = await seq.transaction();
  try {
    let res = (
      await Topic.findOne({
        where: {
          topic_id,
        },
        include: [
          {
            model: Comment,
          },
        ],
      })
    ).get({ plain: true });
    res.comments.forEach(async (item) => {
      const res = await this.deleteComment(item.id);
      console.log(res, '==');
    });
    const result = await Topic.destroy({
      where: {
        topic_id,
      },
    });
    if (result) {
      await t.commit();
      return SimpleData(200, '删除成功');
    }
  } catch (error) {
    console.log(error);
    await t.rollback();
    return SimpleData(500, '删除失败');
  }
};
//删除评论
module.exports.deleteComment = async (id) => {
  const t = await seq.transaction();
  try {
    const res = (
      await Comment.findOne({
        where: { id },
        include: [
          {
            model: Comment,
            as: 'Comments',
          },
        ],
      })
    ).get({ plain: true });
    res.Comments.forEach(async (item) => {
      await Comment.destroy({
        where: {
          id: item.id,
        },
      });
    });
    const result = await Comment.destroy({
      where: {
        id,
      },
    });
    if (result) {
      t.commit();
      return SimpleData(200, '删除成功');
    }
  } catch (error) {
    console.log(error);
    t.rollback();
    return SimpleData(500, '删除失败');
  }
};
//文章增加浏览量
module.exports.upTopicViews = async (topic_id, views) => {
  const result = Topic.update(
    {
      views: views + 1,
    },
    {
      where: {
        topic_id,
      },
    }
  );
};

module.exports.getTopicTypes = async () => {
  const result = await Types.findAll({
    attributes: {
      exclude: ['created_time', 'updated_time'],
    },
  });
  return SuccessData(result);
};

module.exports.postComment = async (params) => {
  const result = (
    await Comment.create({
      ...params,
    })
  ).get({ plain: true });
  return SuccessData(result);
};

module.exports.pagingTopic = async ({ offset, limit, title }) => {
  if (limit) {
    offset = (offset - 1) * limit;
  } else {
    offset = 0;
  }
  const result = await Topic.findAndCountAll({
    where: {
      title: {
        [sequelize.Op.like]: '%' + title + '%',
      },
    },
    include: [
      {
        model: User,
        attributes: ['username'],
      },
    ],
    offset,
    limit,
  });
  if (result) {
    return result;
  } else {
    return SimpleData(500, '获取留言列表失败');
  }
};

//通过名字查找分类
module.exports.findTypeByName = async (name) => {
  const result = await Types.findOne({
    where: { name },
  });
  if (result) {
    return SuccessData(result.get({ plain: true }));
  } else {
    return SimpleData(500, '分类不存在');
  }
};

//根据id查询分类
module.exports.findTypeById = async ({ id }) => {
  const res = await Types.findOne({
    where: {
      id,
    },
  });
  if (res) {
    return SuccessData(res.get({ plain: true }));
  } else {
    return SimpleData(500, '分类不存在');
  }
};

//查询类型
module.exports.pagingType = async ({ offset, limit, name }) => {
  if (limit) {
    offset = (offset - 1) * limit;
  } else {
    offset = 0;
  }
  const result = await Types.findAndCountAll({
    where: {
      name: {
        [sequelize.Op.like]: '%' + name + '%',
      },
    },
    offset,
    limit,
  });
  if (result) {
    return result;
  } else {
    return SimpleData(500, '获取分类列表失败');
  }
};
